const fs = require('fs')
const http = require('http')
const path = require('path')
const os = require('os')



let filepath = path.join(__dirname,'logs', getTime() + '.txt')
//首先创建一个web服务对象
const connet = http.createServer()
//监听客户端/浏览器的请求， 在请求时触发
connet.on('request',(req,res)=>{
    let time = getTime(1)
    let method = req.method;
    let agent = req.headers['user-agent'];
    let ip = req.socket.remoteAddress
    let uri = req.url
    //拼接内容
    let logData = `${ip} - ${time} - ${method} - ${uri} - ${agent}${os.EOL}`
    // fs.writeFile(filepath, html, (err) => {
    //     if (err) {
    //         console.log('创建文件失败');
    //     } else {
    //         console.log('成功');
    //     }
    // })
    fs.appendFile(filepath, logData, err => { });
    res.end();

})
//指定端口并监听
 connet.listen(3030,()=>{
     console.log("3030启动");
 })
 function  getTime(flag = 0) {
     const data = new Date()
     let year = data.getFullYear() ;
     let mouth = ((data.getMonth() + 1) + '').padStart(2, '0');
     let date = (data.getDate() + '').padStart(2, '0');
     let hour = (data.getHours() + '').padStart(2, '0');
     let minut = (data.getMinutes() + '').padStart(2, '0');
     let sec = (data.getSeconds() + '').padStart(2, '0');
     if(flag === 0){
         return `${year} - ${mouth} - ${date}`
     }
     return `${year} - ${mouth} - ${date} ${hour}:${minut}:${sec}`
 }